package com.fly.views.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.fly.core.exception.ValidateException;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Controller
@RequestMapping("/file")
public class FileController
{
    File root = new File("upload");
    
    @PostMapping("/upload")
    public String upload(@RequestParam MultipartFile[] files)
        throws IOException
    {
        if (files == null || files.length == 0)
        {
            throw new ValidateException("files is null");
        }
        String date = DateFormatUtils.format(System.currentTimeMillis(), "yyyyMMdd");
        String dir = root.getCanonicalPath() + File.separator + date + File.separator;
        new File(dir).mkdirs();
        
        // 保存文件
        Arrays.stream(files).filter(file -> StringUtils.isNotBlank(file.getOriginalFilename())).forEach(file -> {
            try
            {
                File newFile = new File(dir + file.getOriginalFilename());
                FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(newFile));
                log.info("###### file upload to: {}", dir);
            }
            catch (IOException e)
            {
                log.error(e.getMessage(), e);
            }
        });
        return "redirect:/index";
    }
    
    @GetMapping(value = "/down/{index}", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public void down(@PathVariable int index, HttpServletResponse response)
        throws IOException
    {
        List<File> files = FileUtils.listFiles(root, null, true).stream().filter(f -> f.isFile()).sorted(Comparator.comparing(File::getAbsolutePath)).collect(Collectors.toList());
        if (index >= 0 && index < files.size())
        {
            File file = files.get(index);
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), StandardCharsets.UTF_8.name()));
            response.setHeader("Cache-Control", "no-store, no-cache");
            FileCopyUtils.copy(new FileInputStream(file), response.getOutputStream());
        }
    }
    
    @GetMapping(value = "/clear")
    public String clear()
        throws IOException
    {
        if (root.exists())
        {
            FileUtils.cleanDirectory(root);
        }
        return "redirect:/index";
    }
    
    @GetMapping(value = "/delete/{index}")
    public String delete(@PathVariable int index)
    {
        List<File> files = FileUtils.listFiles(root, null, true).stream().filter(f -> f.isFile()).sorted(Comparator.comparing(File::getAbsolutePath)).collect(Collectors.toList());
        if (index >= 0 && index < files.size())
        {
            files.get(index).delete();
        }
        return "redirect:/index";
    }
}
